import React, {useEffect, useState, useRef} from 'react';
import {Button, message} from 'antd';
import {usePromiseLoading} from "../../../hooks";

export const useGetCaptchaButton = (props) => {
  const {beforeGet, getCaptchaUrl} = props;

  const [waitCount, setWaitCount] = useState(0);
  const timer = useRef();
  const startCountDown = () => setWaitCount(59);
  const [getCaptchaFn, loading] = usePromiseLoading(async (data) => {
    const resp = await $request(getCaptchaUrl, data);
    message.success('验证码发送成功');
    startCountDown();
  });

  const onGetCaptcha = async () => {
    const resp = await beforeGet();
    if (resp) {
      getCaptchaFn(resp);
    }
  };

  useEffect(() => {
    if (waitCount > 0) {
      timer.current = setTimeout(() => {
        setWaitCount(count => count - 1);
      }, 1000);
    }
    return () => clearTimeout(timer.current);
  }, [waitCount]);

  return {
    waitCount,
    onGetCaptcha,
    loading,
  };
};

function GetCaptchaButton(props) {
  const {waitCount, onGetCaptcha, ...otherProps} = props;
  return (
    <Button block disabled={waitCount} onClick={onGetCaptcha} {...otherProps}>
      {waitCount > 0 ? `${waitCount}秒后重试` : '获取验证码'}
    </Button>
  );
}

export default GetCaptchaButton;
